﻿using DevExpress.Utils;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using Lamex.Library.CommonClass;
using Lamex.SIESystemManager.BLL;
using Lamex.SIESystemManager.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.SIESystemManager.UI
{
    public partial class FrmBIEMachineHours : frmBaseDataForm
    {
        public FrmBIEMachineHours()
        {
            InitializeComponent();
            DateEditFormat();
            InitializeForm();
            ucTextEditDate.CaptionVisible = true;
            ucTextEditVerNo.CaptionVisible = true;
        }

        private void FrmBIEMachineHours_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        protected override void InitializeForm()
        {
            _SummaryView = new DevGridView(gridView2);
            gridView2.DoubleClick += new EventHandler(OnGridViewDoubleClick); //主表DoubleClict
            frmGridViewCust.RegisterGrid(gridView2);
            DevStyle.SetGridControlLayout(gridControl2, false);//表格设置   

            DevStyle.SetSummaryGridViewLayout(gridView2);
            DevStyle.SetDetailGridViewLayout(gridView2);
            ShowSummary(); //下载显示数据.
            tpSummary = xtraTabPage1;
            tcBusiness = xtraTabControl1;
            tpSummary.PageVisible = true;
            //tpDetail.PageVisible = false;
            tcBusiness.ShowTabHeader = DefaultBoolean.True;
            tcBusiness.SelectedTabPage = tpSummary;
            //ShowSummaryPage(true); //一切初始化完毕後显示SummaryPage        
        }
        private void ShowSummary()
        {
            try
            {
                xtraTabPage2.PageEnabled = false;
                xtraTabPage1.PageEnabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void DateEditFormat()
        {
            var formatString = "yyyy-MM";
            dateStart.Properties.DisplayFormat.FormatString = "yyyy-MM";
            dateStart.Properties.Mask.EditMask = formatString;
            dateStart.Properties.VistaCalendarInitialViewStyle = DevExpress.XtraEditors.VistaCalendarInitialViewStyle.YearView;
            dateStart.Properties.VistaCalendarViewStyle = DevExpress.XtraEditors.VistaCalendarViewStyle.YearView;

            dateEnd.Properties.DisplayFormat.FormatString = "yyyy-MM";
            dateEnd.Properties.Mask.EditMask = formatString;
            dateEnd.Properties.VistaCalendarInitialViewStyle = DevExpress.XtraEditors.VistaCalendarInitialViewStyle.YearView;
            dateEnd.Properties.VistaCalendarViewStyle = DevExpress.XtraEditors.VistaCalendarViewStyle.YearView;


            //dateStart.Text = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            //dateEnd.Text = DateTime.Now.AddDays(6).ToString("yyyy-MM-dd");

        }
        /// <summary>
        /// 根据起始和截止日期得到临时表
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        private DataTable GetTempTable(string startTime, string endTime)
        {
            string sql = @"SELECT 
       'D21' AS NUMBER
      ,[PartNo]
      ,[DrawingNo]
	  ,Program_Name as Program_Name
	  ,CONVERT(decimal , SUBSTRING([Process_Time],1,2))*3600+
	  CONVERT(decimal , SUBSTRING([Process_Time],4,2))*60+
	  CONVERT(decimal , SUBSTRING([Process_Time],7,2)) as Process_Time
	  ,COUNT(1) AS COUNTS
  FROM [Edgeband_Program].[dbo].[BIMA_Machine_Time_Data]
  where PartNO !='' and  CONVERT(decimal , SUBSTRING([Process_Time],1,2))*3600+
	  CONVERT(decimal , SUBSTRING([Process_Time],4,2))*60+
	  CONVERT(decimal , SUBSTRING([Process_Time],7,2))>=3 and  CONVERT(decimal , SUBSTRING([Process_Time],1,2))*3600+
	  CONVERT(decimal , SUBSTRING([Process_Time],4,2))*60+
	  CONVERT(decimal , SUBSTRING([Process_Time],7,2))<=600 {0}
  GROUP BY  [PartNo] ,[DrawingNo],Program_Name,CONVERT(decimal , SUBSTRING([Process_Time],1,2))*3600+
	  CONVERT(decimal , SUBSTRING([Process_Time],4,2))*60+
	  CONVERT(decimal , SUBSTRING([Process_Time],7,2))
  union all
SELECT 
      'D11' AS NUMBER  
      ,[PARTNO]
      ,[DRAWINGNO]
	  ,BARCODE as Program_Name
	  ,CEILING([OP_TIME]/10) as Process_Time
	  ,COUNT(1) as COUNTS
  FROM [Edgeband_Program].[dbo].[PuH_Machine_Time_Data]
   where PARTNO !='' and CEILING([OP_TIME]/10)>=3 and  CEILING([OP_TIME]/10)<=600  {1}
  GROUP BY [PARTNO],[DRAWINGNO],BARCODE,CEILING([OP_TIME]/10)";
            sql = string.Format(sql, "and Insert_Time>='" + startTime + "' and Insert_Time<='" + endTime + "'",
                "and DATE>='" + startTime + "' and DATE<='" + endTime + "'");

            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            return dt;
        }

        /// <summary>
        /// 机器时间计算
        /// </summary>
        /// <param name="sender"></param>
        public override void DoMachineTime(IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Machine_Time", "LamexMESManager")) return;
            #endregion
            if (string.IsNullOrEmpty(dateStart.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择开始时间", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(dateEnd.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择结束时间", "提示", MessageBoxButtons.OK);
                return;
            }
            SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
            //using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("机器时间生成中", "请稍后......", new Size(400, 80)))
            //{
            //起始日期为所选月份第一天;截止日期为所选月份最后一天
            string startTime = dateStart.Text + "-01";
            DateTime enday = Convert.ToDateTime(dateEnd.Text + "-01");
            string endTime = enday.AddDays(1 - enday.Day).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
            GetMachineTable(GetTempTable(startTime, endTime));
            DoView(null);
            base.DoMachineTime(sender);
            SplashScreenTool.CloseSplashScreen();
            //}
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        public override void DoEdit(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Machine_Time", "LamexMESManager")) return;
            #endregion
            if (gridView2.SelectedRowsCount == 0)
            {
                MessageBox.Show("【没有选中要删除要修改的数据！】");
                return;
            }
            int m = gridView2.FocusedRowHandle;
            DataRow dr = gridView2.GetDataRow(m);
            KeysName = dr["IDNO"].ToString();
            xtraTabPage1.PageEnabled = false;
            xtraTabPage2.PageEnabled = true;
            xtraTabPage2.PageVisible = true;

            IsEdit = "编辑";
            xtraTabPage2.Tag = "编辑";

            //***********************加载数据****************************//

            ucTextEditVerNo.Text = dr["VER_NO"].ToString();
            ucTextEditDate.Text = dr["DATE_TS"].ToString();
            if (dr["Flag"].ToString() == "True")
                comboBoxEditFlag.Text = "Y";
            else
                comboBoxEditFlag.Text = "N";

            base.DoEdit(sender);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        public override void DoSave(IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Machine_Time", "LamexMESManager")) return;
            #endregion
            if (IsEdit == "编辑")
            {
                B_IE_Machine_VersionInfo model = new B_IE_Machine_VersionInfo();
                model.IDNO = int.Parse(KeysName);
                model.VER_NO = ucTextEditVerNo.Text;
                model.DATE_TS = Convert.ToDateTime(ucTextEditDate.Text);
                if (comboBoxEditFlag.Text == "Y")
                    model.Flag = true;
                else
                    model.Flag = false;
                if (BaseFactory<B_IE_Machine_Version>.Instance.Update(model))
                {
                    MessageBox.Show("保存存成功！");

                }
                else
                {
                    MessageBox.Show("保存存失败！");
                }
            }

            xtraTabPage2.PageEnabled = false;
            xtraTabPage1.PageEnabled = true;
            DoView(null);
            base.DoSave(sender);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        public override void DoDelete(Lamex.Interface.IButtonInfo sender)
        {
            #region 按钮权限
            if (!BuildSqlHelper.IsExistList("B_IE_Machine_Time", "LamexMESManager")) return;
            #endregion
            if (gridView2.SelectedRowsCount == 0)
            {
                MessageBox.Show("【没有选中要删除的数据，请选择好数据！】");
                return;
            }
            int m = gridView2.FocusedRowHandle;
            DataRow dr = gridView2.GetDataRow(m);
            string verNo = dr["VER_NO"].ToString();
            if (dr != null)
            {
                if (BaseFactory<B_IE_Machine_Version>.Instance.Delete(dr["IDNO"].ToString()))
                {
                    //同时删除机器时间表
                    string sql = @"delete from  [LamexMESManager].[dbo].[B_IE_Machine_Time] where Ver_No='" + verNo + "'";
                    BaseBuildSql.ExecuteNonQuery(sql);
                    MessageBox.Show("【数据删除成功！】");

                }
                else
                {
                    MessageBox.Show("【数据删除失败！】");

                }
            }
            DoView(null);
            base.DoDelete(sender);
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        public override void DoView(IButtonInfo sender)
        {
            string sqlWhere = "";
            string sql = " select * from  [LamexMESManager].[dbo].[B_IE_Machine_Version] where 1=1 ";
            sql = sql + sqlWhere;
            DataTable dt = BaseBuildSql.GetDataTableBySql(sql);
            DoBindingSummaryGrid(dt);
            base.DoView(sender);
        }
        /// <summary>
        /// 得到机器数据
        /// </summary>
        private void GetMachineTable(DataTable dt)
        {
            //string strFiled = "";
            //string filedValue = "";
            //string PartNo = "";
            //string DrawingNo = "";
            //string ProcessName = "";
            //string MachineName = "";
            string Ver_No = dateStart.Text.Replace("-", "") + "_" + dateEnd.Text.Replace("-", "");//每次固定版本值
            double MachineTime = 0;
            double Count = 0, MaxValue = 0, MinValue = 0, MaxTime = 0, MinTime = 0;
            double AvgTime = 0, AvgTime1 = 0, AvgTime2 = 0, MaxTime1 = 0, MaxTime2 = 0, MinTime1 = 0, MinTime2 = 0;
            DataTable tableInsert = GetTable_Machine_Time();
            //去掉重复PartNumber,然后代入循环得到每一个PartNumber的机器时间
            DataView dv = dt.DefaultView;
            DataTable dtNew = dv.ToTable(true, "PartNo");
            try
            {
                if (dtNew.Rows.Count > 0)
                {
                    for (int i = 0; i < dtNew.Rows.Count; i++)
                    {
                        /*1、根据部件号获取出现的次数
                          2、根据部件号获取最大、最小计算值
                          3、根据最大、最小计算值获取时间
                        */
                        // Count = Convert.ToInt32(dt.Select("PartNo='" + dtNew.Rows[i][0] + "'").CopyToDataTable().DefaultView.ToTable(true, "PartNo", "COUNTS").Compute("count(PartNo)", "true"));
                        Count = Convert.ToDouble(dt.Select("PartNo='" + dtNew.Rows[i][0] + "'").CopyToDataTable().Compute("count(PartNo)", "true"));
                        MaxValue = Convert.ToDouble(dt.Select("PartNo='" + dtNew.Rows[i][0] + "'").CopyToDataTable().Compute("max(COUNTS)", ""));
                        MinValue = Convert.ToDouble(dt.Select("PartNo='" + dtNew.Rows[i][0] + "'").CopyToDataTable().Compute("min(COUNTS)", ""));
                        //Couts全为1时的第一次最大值
                        MaxTime = Convert.ToDouble(dt.Select("PartNo='" + dtNew.Rows[i][0] + "' and COUNTS='" + MaxValue + "'").CopyToDataTable().Compute("max(Process_Time)", ""));
                        //Couts全为1时的第一次最小值
                        MinTime = Convert.ToDouble(dt.Select("PartNo='" + dtNew.Rows[i][0] + "' and COUNTS='" + MinValue + "'").CopyToDataTable().Compute("min(Process_Time)", ""));
                        //Couts全为1时的第一次平均值
                        AvgTime = Math.Ceiling(Convert.ToDouble(dt.Select("PartNo='" + dtNew.Rows[i][0] + "'").CopyToDataTable().Compute("avg(Process_Time)", "")));

                        //相同次数大于1 max(COUNTS)>1
                        if (MaxValue > 1)
                        {
                            MachineTime = MaxTime;
                        }
                        else
                        {
                            //Counts=1时出现记录数为1
                            if (Count == 1)
                            {
                                MachineTime = 0;
                            }
                            //Counts=1时出现记录数为小于5
                            else if (Count > 1 && Count < 5)
                            {
                                if (MaxTime <= 60 && MaxTime - MinTime <= 6)
                                    MachineTime = AvgTime;
                                else if (MaxTime > 60 && MaxTime - MinTime <= 10)
                                    MachineTime = AvgTime;
                                else
                                    MachineTime = 0;
                            }
                            //Counts=1时出现记录数为小于10
                            else if (Count >= 5 && Count < 10)
                            {
                                DataTable dtTemp = dt.Select("PartNo='" + dtNew.Rows[i][0] + "'").CopyToDataTable();
                                List<double> list = new List<double>();
                                for (int j = 0; j < dtTemp.Rows.Count; j++)
                                {
                                    list.Add(Convert.ToDouble(dtTemp.Rows[j]["Process_Time"]));
                                }
                                //去掉最大值
                                list.Remove(list.Max());
                                //去掉最小值
                                list.Remove(list.Min());
                                //得到最大值1
                                MaxTime1 = list.Max();
                                //得到最小值1
                                MinTime1 = list.Min();
                                //得到平均值1
                                AvgTime1 = Math.Ceiling(list.Average());
                                if (MaxTime <= 60)
                                {
                                    if (MaxTime - MinTime <= 6)
                                        MachineTime = AvgTime;
                                    else if (MaxTime1 - MinTime1 <= 6)
                                        MachineTime = AvgTime1;
                                    else
                                        MachineTime = 0;
                                }
                                else if (MaxTime > 60)
                                {
                                    if (MaxTime - MinTime <= 10)
                                        MachineTime = AvgTime;
                                    else if (MaxTime1 <= 60 && MaxTime1 - MinTime1 <= 6)
                                        MachineTime = AvgTime1;
                                    else if (MaxTime1 > 60 && MaxTime1 - MinTime1 <= 10)
                                        MachineTime = AvgTime1;
                                    else
                                        MachineTime = 0;
                                }
                            }
                            //Counts=1时出现记录数为大于10
                            else if (Count > 10)
                            {
                                DataTable dtTemp = dt.Select("PartNo='" + dtNew.Rows[i][0] + "'").CopyToDataTable();
                                List<double> list = new List<double>();
                                for (int j = 0; j < dtTemp.Rows.Count; j++)
                                {
                                    list.Add(Convert.ToDouble(dtTemp.Rows[j]["Process_Time"]));
                                }
                                //去掉最大值
                                list.Remove(list.Max());
                                //去掉最小值
                                list.Remove(list.Min());
                                //得到最大值1
                                MaxTime1 = list.Max();
                                //得到最小值1
                                MinTime1 = list.Min();
                                //得到平均值1
                                AvgTime1 = Math.Ceiling(list.Average());
                                //再次去掉最大值
                                list.Remove(list.Max());
                                //去掉再次最小值
                                list.Remove(list.Min());
                                //得到最大值2
                                MaxTime2 = list.Max();
                                //得到最小值2
                                MinTime2 = list.Min();
                                //得到平均值2
                                AvgTime2 = Math.Ceiling(list.Average());
                                if (MaxTime <= 60)
                                {
                                    if (MaxTime - MinTime <= 6)
                                        MachineTime = AvgTime;
                                    else if (MaxTime1 - MinTime1 <= 6)
                                        MachineTime = AvgTime1;
                                    else if (MaxTime2 - MinTime2 <= 6)
                                        MachineTime = AvgTime1;
                                    else
                                        MachineTime = 0;
                                }
                                else if (MaxTime > 60)
                                {
                                    if (MaxTime - MinTime <= 10)
                                        MachineTime = AvgTime;
                                    if (MaxTime1 <= 60)
                                    {
                                        if (MaxTime1 - MinTime1 <= 6)
                                            MachineTime = AvgTime1;
                                        else if (MaxTime2 - MinTime1 <= 6)
                                            MachineTime = AvgTime2;
                                        else
                                            MachineTime = 0;
                                    }
                                    else if (MaxTime1 > 60)
                                    {
                                        if (MaxTime1 - MinTime1 <= 10)
                                            MachineTime = AvgTime1;
                                        else if (MaxTime2 <= 60 && MaxTime2 - MinTime1 <= 6)
                                            MachineTime = AvgTime2;
                                        else if (MaxTime2 > 60 && MaxTime2 - MinTime1 <= 10)
                                            MachineTime = AvgTime2;
                                        else
                                            MachineTime = 0;
                                    }

                                }
                            }
                        }

                        //添加版本号并插入数据库B_IE_Machine_Time
                        DataTable dtList = dt.Select("PartNo='" + dtNew.Rows[i][0] + "'").CopyToDataTable();
                        DataRow dr = tableInsert.NewRow();
                        dr["Machine_Name"] = dtList.Rows[0]["NUMBER"].ToString();
                        dr["Part_No"] = dtList.Rows[0]["PartNo"].ToString();
                        dr["Drawing_No"] = dtList.Rows[0]["DrawingNo"].ToString();
                        dr["Program_Name"] = dtList.Rows[0]["Program_Name"].ToString();
                        dr["Process_Time"] = MachineTime;
                        dr["Ver_No"] = Ver_No;
                        dr["Date_TS"] = DateTime.Now;
                        tableInsert.Rows.Add(dr);


                    }
                }

                //添加版本号并插入数据库B_IE_Machine_Time/B_IE_Machine_Version
                if (BaseBuildSql.ExcuteInsert(tableInsert, "B_IE_Machine_Time"))
                {
                    tableInsert = new DataTable();
                }
                string sqlVer = @"insert into [LamexMESManager].[dbo].[B_IE_Machine_Version]([VER_NO],[DATE_TS],[Flag])
                                              Values('" + Ver_No + "',GETDATE(),'1')";
                BaseBuildSql.ExecuteNonQuery(sqlVer);
            }
            catch (Exception EX)
            {

                DevExpress.XtraEditors.XtraMessageBox.Show("机器时间获取失败" + EX.Message, "提示", MessageBoxButtons.OK);
            }
        }

        public DataTable GetTable_Machine_Time()
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[] {   
         new DataColumn("Machine_Name",typeof(string)),  
         new DataColumn("Part_No",typeof(string)),  
         new DataColumn("Drawing_No",typeof(string)), 
         new DataColumn("Program_Name",typeof(string)), 
         new DataColumn("Process_Time",typeof(int)), 
         new DataColumn("Ver_No",typeof(string)), 
         new DataColumn("Date_TS",typeof(DateTime))});
            return dt;
        }
    }
}
